/**
 * Created by DevilsEyes on 2016/5/14.
 */
'use strict';

let api = require('./api');

let TASK_LIST = {
    checkFile: require('./checkFile')
};

// let interval = 1000 * 60 * 2;
let interval = 1000;

let init = ()=> {

    return new Promise((O, X)=> {

        let PromiseList = [];

        {
            let type = 'checkFile';
            let p = api.regist(type, new Date().getTime() + TASK_LIST[type].next);
            PromiseList.push(p);
        }

        Promise.all(PromiseList).then(()=> {
                O();
            })
            .catch((e)=> {
                console.log(e);
            })

    })

};

let start = ()=> {

    setInterval(()=> {

        api.getAvaliable()
            .then((tasks)=> {
                tasks.map((task)=> {

                    let id = task._id;
                    let type = api.getType(task.type);
                    let json = JSON.parse(task.json || 'null');

                    TASK_LIST[type]
                        .task(json)
                        .then(()=> {
                            api.regist(type, new Date().getTime() + TASK_LIST[type].next);
                            api.removeById(id);
                        })
                        .catch(()=> {

                        })
                })
            })
    }, interval);

};

module.exports = {
    init: ()=> {

        //todo test:清除任务列表
        api.clearAll()
            .then(()=>api.getAll())
            .then((tasks)=> {

                if (tasks.length == 0) {
                    init()
                        .then(()=> {
                            start();
                        })
                } else {
                    start();
                }
            })
            .catch((e)=>console.log(e));

    }
};